package lhd.mybatis_simple_log.actions;

import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.ui.Messages;
import lhd.mybatis_simple_log.icons.MybatisSimpleLogIcons;
import lhd.mybatis_simple_log.utils.LogUtil;
import org.jetbrains.annotations.NotNull;

import java.awt.datatransfer.StringSelection;

/**
 * 解析并复制日志为sql语句
 *
 * @author lhd
 * @since 2025/6/10 16:16
 */
public class ParseAndCopyAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        // 获取当前编辑器实例
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        if (editor == null) {
            return;
        }
        SelectionModel selectionModel = editor.getSelectionModel();

        // 获取选中的文本内容
        String selectedText = selectionModel.getSelectedText();
        if (selectedText != null && !selectedText.isEmpty()) {

            String parsingSql = null;
            try {
                parsingSql = LogUtil.parsingLogToSql(selectedText);
            } catch (Exception ex) {
                Messages.showMessageDialog("The log parsing failed. Please check whether the selected log content is right", "Tips", Messages.getWarningIcon());
            }

            // 如果解析失败，提示用户
            if (parsingSql == null) {
                Messages.showMessageDialog("The log parsing failed. Please check whether the selected log content is right", "Tips", Messages.getWarningIcon());
                return;
            }


            // 复制到剪贴板
            CopyPasteManager.getInstance().setContents(new StringSelection(parsingSql));
        }
    }

    @Override
    public void update(AnActionEvent e) {
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        e.getPresentation().setIcon(MybatisSimpleLogIcons.ICON);
        e.getPresentation().setEnabled(
                editor != null && editor.getSelectionModel().hasSelection()
                        && editor.getSelectionModel().getSelectedText() != null
                        && LogUtil.isMybatisSqlLog(editor.getSelectionModel().getSelectedText()));
    }

    @Override
    public @NotNull ActionUpdateThread getActionUpdateThread() {
        return ActionUpdateThread.EDT;
    }


}
